package edu.csu.smartpark.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import edu.csu.smartpark.model.DO.EnterpriseDO;
import edu.csu.smartpark.model.DO.UserDO;
import edu.csu.smartpark.model.DTO.EnterpriseBasicDTO;
import edu.csu.smartpark.model.DTO.EnterpriseDTO;
import edu.csu.smartpark.model.DTO.EnterpriseQueryDTO;
import edu.csu.smartpark.model.VO.EnterpriseVO;
import edu.csu.smartpark.model.VO.PageVO;
import edu.csu.smartpark.model.common.BusinessException;
import edu.csu.smartpark.model.common.MsgEntity;
import edu.csu.smartpark.service.EnterpriseService;
import edu.csu.smartpark.service.UserService;
import edu.csu.smartpark.util.Constants;
import edu.csu.smartpark.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;

@RestController
@Slf4j
@Api(tags = "企业管理")
@RequestMapping("/enterprise")
public class EnterpriseController extends BaseController {

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private UserService userService;

    @GetMapping("/list/all")
    public MsgEntity getAllEnterprise(String enterpriseName) {

        return new MsgEntity("Success", MsgEntity.SUCCESS, enterpriseService.getAllEnterprise(enterpriseName));
    }

    @GetMapping("/get")
    public MsgEntity getEnterpriseInfo(@RequestParam("enterpriseId") String enterpriseId) throws BusinessException{
        EnterpriseDO enterpriseDO = enterpriseService.getEnterpriseInfoById(enterpriseId);

        if (enterpriseDO == null) {
            throw new BusinessException("-1", "enterprise is not exist");
        }

        return new MsgEntity("Success", MsgEntity.SUCCESS, enterpriseDO);
    }

    @ApiOperation("查看我创建的企业")
    @GetMapping("/my")
    public MsgEntity getEnterpriseInfo() {
        String userid = getUserId();

        return new MsgEntity("Success", MsgEntity.SUCCESS, enterpriseService.getEnterpriseInfoByCreatorId(userid));
    }

    @PostMapping("/update")
    public MsgEntity modifyEnterpriseInfo(@RequestBody @Validated EnterpriseBasicDTO enterpriseBasicDTO) throws BusinessException {

        if (enterpriseService.updateEnterpriseInfo(enterpriseBasicDTO) == 1) {
            return new MsgEntity("Success", MsgEntity.SUCCESS, enterpriseService.getEnterpriseInfoById(enterpriseBasicDTO.getId()));
        }

        throw new BusinessException("-1", "enterprise update failed");
    }

    @PostMapping("/add")
    @ResponseBody
    @RequiresRoles(value = Constants.CommonUser)
    public MsgEntity addEnterprise(
            @RequestParam("code") String code,
            @RequestParam("name") String name,
            @RequestParam("logo") MultipartFile logo,
            @RequestParam("briefIntroduction") String briefIntroduction,
            @RequestParam("phone") String phone,
            @RequestParam("type") int type,
            @RequestParam("address") String address,
            @RequestParam("legalPersonName") String legalPersonName,
            @RequestParam("establishmentDate") String establishmentDate,
            @RequestParam("businessLicense") MultipartFile businessLicense,
            @RequestParam("businessScope") String businessScope,
            @RequestParam("legalPersonCertificate") MultipartFile legalPersonCertificate,
            @RequestParam("identityNumber") String identityNumber,
            @RequestParam("parkId") String parkId,
            @RequestParam("entryTime") @DateTimeFormat(pattern="yyyy-MM-dd") Date entryTime) throws BusinessException {
        if (enterpriseService.checkEnterpriseCode(code) > 0) {
            throw new BusinessException("-1", "code is exist");
        }

        String userId = getUserId();
        UserDO userDO = userService.getUserById(userId);

        EnterpriseDTO enterpriseDTO = new EnterpriseDTO();
        enterpriseDTO.setCode(code);
        enterpriseDTO.setName(name);
        enterpriseDTO.setLogo(logo);
        enterpriseDTO.setBriefIntroduction(briefIntroduction);
        enterpriseDTO.setPhone(phone);
        enterpriseDTO.setType(type);
        enterpriseDTO.setAddress(address);
        enterpriseDTO.setLegalPersonName(legalPersonName);
        enterpriseDTO.setEstablishmentDate(establishmentDate);
        enterpriseDTO.setBusinessLicense(businessLicense);
        enterpriseDTO.setBusinessScope(businessScope);
        enterpriseDTO.setLegalPersonCertificate(legalPersonCertificate);
        enterpriseDTO.setIdentityNumber(identityNumber);
        enterpriseDTO.setParkId(parkId);
        enterpriseDTO.setEntryTime(entryTime);

        // 园区管理员提交创建企业请求
        if (userDO.getRoles().contains(Constants.ParkAdministrator)) {
            // 重设园区id，避免风险
            enterpriseDTO.setParkId(userDO.getParkId());
            return new MsgEntity("Success", MsgEntity.SUCCESS, enterpriseService.createEnterprise(enterpriseDTO, userId));
        }

        // 其他用户有所属企业，则无法创建企业
        if (StringUtil.isEmpty(userDO.getEnterpriseId())) {
            String enterpriseId = enterpriseService.createEnterprise(enterpriseDTO, userId);

            // 更新用户所属企业
            userService.updateEnterpriseOfUser(userId, enterpriseId);
            return new MsgEntity("Success", MsgEntity.SUCCESS, enterpriseId);
        } else {
            throw new BusinessException("-2", "user already have the enterprise");
        }
    }

    @GetMapping("/check_code")
    public MsgEntity checkEnterpriseCode(@RequestParam("code") String enterpriseCode) {
        return new MsgEntity("Success", MsgEntity.SUCCESS, enterpriseService.checkEnterpriseCode(enterpriseCode));
    }

    @ApiOperation(value = "企业入驻批量审核通过")
    @PostMapping("/audit/pass")
    @RequiresRoles(value = {Constants.SystemAdministrator, Constants.ParkAdministrator}, logical = Logical.OR)
    public MsgEntity enterpriseAuditPass(@RequestBody List<String> ids) {
        int result = 0;
        for (String id : ids) {
            if (enterpriseService.getEnterpriseInfoById(id).getStatus() == 0) {
                result += enterpriseService.updateEnterpriseStatus(id, 1);
            }
        }
        return new MsgEntity("Success", MsgEntity.SUCCESS, result);
    }

    @PostMapping("/query")
    public MsgEntity queryEnterprise(@RequestBody EnterpriseQueryDTO enterpriseQueryDTO) throws BusinessException{
        PageVO<EnterpriseVO> res = enterpriseService.queryEnterprise(enterpriseQueryDTO);
        return new MsgEntity("success", MsgEntity.SUCCESS, res);
    }
}
